package cn.xinfei.xdecision.common.service.datax.datamanage.v2.impl;

import cn.xinfei.xdecision.common.dao.datax.datamanage.v2.OrganUserMapper;
import cn.xinfei.xdecision.common.dao.datax.datamanage.v2.VariableParamMapper;
import cn.xinfei.xdecision.common.model.datax.datamanage.v2.OrganUser;
import cn.xinfei.xdecision.common.model.datax.datamanage.v2.VariableParam;
import cn.xinfei.xdecision.common.service.datax.datamanage.v2.VariableParamService;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class VariableParamServiceImpl extends ServiceImpl<VariableParamMapper, VariableParam> implements VariableParamService {

    @Resource
    VariableParamMapper variableParamMapper;

    @Resource
    OrganUserMapper organUserMapper;

    @Override
    public List<String> getVarParamsDistinct(Set<String> varCodes) {
        if (CollectionUtils.isEmpty(varCodes)) {
            return Collections.emptyList();
        }
        return variableParamMapper.getVarParamCodesDistinct(varCodes);
    }

    @Override
    public Set<String> getVarParamCode(String varCode) {
        return variableParamMapper.getVarParamCode(varCode);
    }

    @Override
    public Map<String, Map<String,String>> getVarAndParamCode(Set<String> varCodes) {
        return variableParamMapper.getVarCodeAndParams(varCodes);
    }

    @Override
    public List<VariableParam> getAllVarParamCodes() {
        return new LambdaQueryChainWrapper<>(variableParamMapper)
                .select(VariableParam::getVarCode, VariableParam::getParamVariableCode)
                .eq(VariableParam::getIsDeleted, 'N')
                .list();
    }

    @Override
    public Set<String> getDepVarParamCode(String varCode, Long organId) {
        List<VariableParam> depVarParams = new LambdaQueryChainWrapper<>(variableParamMapper)
                .select(VariableParam::getVarCode)
                .eq(StringUtils.isNotBlank(varCode), VariableParam::getParamVariableCode, varCode)
                .eq(Objects.nonNull(organId), VariableParam::getOrganId, organId)
                .list();

        return Optional.ofNullable(depVarParams)
                .orElseGet(Collections::emptyList)
                .stream()
                .filter(Objects::nonNull)
                .map(VariableParam::getVarCode)
                .collect(Collectors.toSet());
    }
}
